<template>
  <div class="category-list-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入分类名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作区域 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>分类列表</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>添加分类
          </el-button>
        </div>
      </template>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="categoryList"
        border
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="name" label="分类名称" min-width="150" />
        <el-table-column prop="description" label="分类描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" min-width="180" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        v-if="total > 0"
        v-model:current-page="queryParams.current"
        v-model:page-size="queryParams.size"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加分类' : '编辑分类'"
      width="500px"
      append-to-body
    >
      <el-form
        ref="categoryFormRef"
        :model="categoryForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryForm.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="分类描述" prop="description">
          <el-input
            v-model="categoryForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入分类描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCategoryList, addCategory, updateCategory, deleteCategory } from '../../api/category'

// 查询参数
const queryParams = reactive({
  current: 1,
  size: 10,
  name: ''
})

// 分类列表数据
const categoryList = ref([])
const total = ref(0)
const loading = ref(false)

// 获取分类列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getCategoryList(queryParams)
    if (res.data) {
      categoryList.value = res.data.records || []
      total.value = res.data.total || 0
      
      // 格式化日期
      categoryList.value.forEach(item => {
        if (item.createTime) {
          const date = new Date(item.createTime)
          item.createTime = date.toLocaleString()
        }
      })
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索按钮点击事件
const handleQuery = () => {
  queryParams.current = 1
  getList()
}

// 重置按钮点击事件
const resetQuery = () => {
  queryParams.name = ''
  handleQuery()
}

// 分页大小改变事件
const handleSizeChange = (size) => {
  queryParams.size = size
  getList()
}

// 页码改变事件
const handleCurrentChange = (current) => {
  queryParams.current = current
  getList()
}

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add') // 'add' 或 'edit'
const submitLoading = ref(false)

// 分类表单
const categoryFormRef = ref(null)
const categoryForm = reactive({
  id: undefined,
  name: '',
  description: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 1, max: 50, message: '分类名称长度不能超过50个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '分类描述长度不能超过200个字符', trigger: 'blur' }
  ]
}

// 添加分类按钮点击事件
const handleAdd = () => {
  dialogType.value = 'add'
  resetCategoryForm()
  dialogVisible.value = true
}

// 编辑分类按钮点击事件
const handleEdit = (row) => {
  dialogType.value = 'edit'
  resetCategoryForm()
  // 填充表单数据
  categoryForm.id = row.id
  categoryForm.name = row.name
  categoryForm.description = row.description
  dialogVisible.value = true
}

// 重置分类表单
const resetCategoryForm = () => {
  if (categoryFormRef.value) {
    categoryFormRef.value.resetFields()
  }
  categoryForm.id = undefined
  categoryForm.name = ''
  categoryForm.description = ''
}

// 提交表单
const submitForm = async () => {
  if (!categoryFormRef.value) return
  
  await categoryFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        if (dialogType.value === 'add') {
          // 添加分类
          await addCategory(categoryForm)
          ElMessage.success('添加成功')
        } else {
          // 编辑分类
          await updateCategory(categoryForm)
          ElMessage.success('修改成功')
        }
        dialogVisible.value = false
        getList()
      } catch (error) {
        console.error(dialogType.value === 'add' ? '添加分类失败:' : '修改分类失败:', error)
        ElMessage.error(dialogType.value === 'add' ? '添加分类失败' : '修改分类失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 删除分类按钮点击事件
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除分类「${row.name}」吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteCategory(row.id)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        getList()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      console.error('删除分类失败:', error)
      ElMessage.error('删除分类失败')
    }
  }).catch(() => {})
}

// 页面加载时获取数据
onMounted(() => {
  getList()
})
</script>

<style scoped>
.category-list-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style>